﻿using UnityEngine;
using System.Collections;

public class AudioFadeManager : MonoBehaviour {

	private float amount = .5f;
	private string nextScene = "";

	public void FadeIn (ref AudioSource source,string sceneName) 
	{
		this.nextScene = sceneName;
		FadeIn(ref source);
	}
	public void FadeOut (ref AudioSource source,string sceneName) 
	{
		this.nextScene = sceneName;
		FadeOut(ref source);
	}

	public void FadeIn (ref AudioSource source) 
	{
		StartCoroutine(FadeInInsert(source));
	}
	public void FadeOut (ref AudioSource source) 
	{
		StartCoroutine(FadeOutInsert(source));
	}

	IEnumerator FadeInInsert(AudioSource source)
	{
		float i = 0;
		source.volume = i;

		while(true)
		{
			if(i < 1)
				i += amount*Time.deltaTime;
			else
				break;

			source.volume = i;
			yield return null;
		}

		if(nextScene != "")
			Application.LoadLevel(nextScene);
	}

	IEnumerator FadeOutInsert(AudioSource source)
	{
		float i = 1;
		source.volume = i;
		
		while(true)
		{
			if(i > 0)
				i -= amount*Time.deltaTime;
			else
				break;
			
			source.volume = i;
			yield return null;
		}

		if(nextScene != "")
			Application.LoadLevel(nextScene);
	}
}
